﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Configuration;

namespace Project.UI.Controllers
{
    public class FilesController : Controller
    {
        
        public ActionResult Upload()
        {
            dynamic d = new ExpandoObject();

            //获取提交的文件
            var files = Request.Files;
            var file = files[0];

            if (files.Count < 1 || file == null)
            {
                d.code = -4;
                d.msg = "上传失败，未检测上传的文件信息!";
            }
            else
            {
                //获取当前时间
                var currentDate = DateTime.Now;
                //获取系统的根路径
                var webRootPath = Server.MapPath("/");
                try
                {
                    //文件后缀//获取文件格式，拓展名
                    var fileExtension = Path.GetExtension(file.FileName).ToLower();    
                    var type = "";

                    //获取 web.config 配置文件中配置数据
                    string imgType = ConfigurationManager.AppSettings["imgtype"];
                    string audioType = ConfigurationManager.AppSettings["audiotype"];
                    string videoType = ConfigurationManager.AppSettings["videotype"];
                    string officeType = ConfigurationManager.AppSettings["officetype"];
                    string fileType = ConfigurationManager.AppSettings["filetype"];
                    //根据后缀匹配相应的文件夹
                    type = Regex.IsMatch(fileExtension, imgType) ? "img"
                           : Regex.IsMatch(fileExtension, audioType) ? "audio"
                           : Regex.IsMatch(fileExtension, videoType) ? "video"
                           : Regex.IsMatch(fileExtension, officeType) ? "office"
                           : Regex.IsMatch(fileExtension, fileType) ? "file"
                           : "";

                    //判断是否有当前日期文件夹
                    var filePath = $"/UploadFiles/{type}/{currentDate:yyyyMMdd}/";
                    if (!Directory.Exists(webRootPath + filePath))
                    {
                        //创建每日存储文件夹
                        Directory.CreateDirectory(webRootPath + filePath);
                    }
                    //判断文件夹不为空时进入
                    if (filePath != null)
                    {
                                           
                        var fileSize = file.ContentLength; 
                        int maxSize = int.Parse(ConfigurationManager.AppSettings["filemaxsize"]);
                        //判断文件大小
                        if (fileSize > maxSize)
                        {
                            d.code = -2;
                            d.msg = "上传的文件不能大于"+(maxSize/1024/1024)+"M!";
                        }
                        else
                        {
                            //保存的文件名称(以名称和保存时间命名)
                            var saveName = file.FileName.Substring(0, file.FileName.LastIndexOf('.')) + "_" + currentDate.ToString("HHmmss") + fileExtension;

                            //保存文件到指定路径（完整路径）
                            file.SaveAs(webRootPath + filePath + saveName);

                            //完整的文件路径
                            var completeFilePath = Path.Combine(filePath, saveName);

                            d.code = 1;
                            d.msg = "上传成功!";
                            d.filepath = completeFilePath;
                        }
                    }
                    else
                    {
                        d.code = -3;
                        d.code = "创建文件夹失败!";
                    }
                }
                catch (Exception ex)
                {
                    d = -5;
                    d.msg = "文件保存失败，异常信息为：" + ex.Message;

                }
            }   
            return Content(JsonConvert.SerializeObject(d), "Application/Json");
        }
    }
}